{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "bb65d3e6-a560-48d0-be41-d0137b98c049",
   "metadata": {},
   "source": [
    "Chapter 08\n",
    "# 提取对角线元素\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b2247080-052b-45b8-bd58-c64455e3ae87",
   "metadata": {},
   "outputs": [],
   "source": [
    "def extract_main_diagonal(matrix):\n",
    "    \n",
    "    rows = len(matrix); cols = len(matrix[0])\n",
    "    size = min(rows, cols)\n",
    "    diagonal = [matrix[i][i] for i in range(size)]\n",
    "    return diagonal"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c11f9803-d43f-45f4-b0da-b2ad7b7a5447",
   "metadata": {},
   "outputs": [],
   "source": [
    "matrix = [[1, 2, 3],\n",
    "          [4, 5, 6]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "fe24ab78-af09-4669-bfaa-4672ba02f091",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 5]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "main_diagonal = extract_main_diagonal(matrix)\n",
    "main_diagonal"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
